import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { setLoading, loginSuccess, loginFailure, clearError } from '../../store/Slice/userSlice'
import { authAPI } from '../../axios/api'
import type { RootState, AppDispatch } from '../../store/index'
import VerifyModal from '../../components/VerifyModal'
import './login.css'

// 导入API类型
import type { LoginRequest } from '../../axios/api'

function Index() {
  const dispatch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const { isLoading, error } = useSelector((state: RootState) => state.user)
  
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [isVerifying, setIsVerifying] = useState(false)
  const [showVerifyModal, setShowVerifyModal] = useState(false)
  const [isVerified, setIsVerified] = useState(false)
  const [showPassword, setShowPassword] = useState(false)

  // 组件加载时检查用户状态
  useEffect(() => {
    const token = localStorage.getItem('token')
    const username = localStorage.getItem('username')
    const userId = localStorage.getItem('userId')
    const role = localStorage.getItem('role')
    
    if (token && username && userId && role) {
      // 如果用户已登录，直接跳转到home页面
      navigate('/home')
    }
  }, [navigate])

  const handleVerification = () => {
    setShowVerifyModal(true)
  }

  const handleVerifySuccess = () => {
    setIsVerified(true)
    setIsVerifying(false)
  }

  const handleVerifyClose = () => {
    setShowVerifyModal(false)
  }

  // 切换密码显示/隐藏
  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword)
  }

  // 登录API调用
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 验证必填字段
    if (!username.trim()) {
      dispatch(loginFailure('请输入用户名'))
      return
    }
    
    if (!password.trim()) {
      dispatch(loginFailure('请输入密码'))
      return
    }
    
    // 验证人机验证
    if (!isVerified) {
      dispatch(loginFailure('请先完成人机验证'))
      return
    }
    
    dispatch(setLoading(true))
    dispatch(clearError())
    
    try {
      const loginData: LoginRequest = {
        account: username.trim(),
        password: password.trim()
      }
      
      const data = await authAPI.login(loginData)
      
      // 保存登录信息到localStorage
      localStorage.setItem('token', data.token)
      localStorage.setItem('username', data.username)
      localStorage.setItem('userId', data.userId.toString())
      localStorage.setItem('role', data.role.toString())
      
      // 更新RTK状态
      dispatch(loginSuccess({
        username: data.username,
        role: data.role,
        userId: data.userId,
        token: data.token
      }))
      
      // 显示成功消息
    //   alert(`登录成功！欢迎 ${data.username}`)
      
      // 跳转到首页
      navigate('/home')
      
    } catch (error) {
      console.error('登录失败:', error)
      dispatch(loginFailure('登录失败，请检查用户名和密码'))
    }
  }

  const handleThirdPartyLogin = (platform: string) => {
    console.log(`${platform} 登录`)
  }

  return (
    <div className="login-container">
      <div className="login-background">
        <img src="/src/assets/loginImg/90.jpg" alt="背景" className="bg-image" />
        <div className="bg-overlay"></div>
      </div>
      
      <div className="login-content">
        <div className="login-card">
          <div className="login-header">
            <h1 className="login-title">数字人登录</h1>
            <p className="login-subtitle">进入3D数字世界</p>
          </div>
          
          <form className="login-form" onSubmit={handleLogin}>
            <div className="input-group">
              <div className="input-wrapper">
                <input
                  type="text"
                  placeholder="用户名/邮箱"
                  value={username}
                  onChange={(e) => {
                    setUsername(e.target.value)
                    if (error) dispatch(clearError())
                  }}
                  className="login-input"
                />
                <div className="input-glow"></div>
              </div>
            </div>
            
            <div className="input-group">
              <div className="input-wrapper password-wrapper">
                <input
                  type={showPassword ? "text" : "password"}
                  placeholder="密码"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value)
                    if (error) dispatch(clearError())
                  }}
                  className="login-input password-input"
                />
                <button
                  type="button"
                  className="password-toggle-btn"
                  onClick={togglePasswordVisibility}
                  tabIndex={-1}
                >
                  {showPassword ? (
                    <svg className="eye-icon" viewBox="0 0 24 24" fill="none">
                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/>
                    </svg>
                  ) : (
                    <svg className="eye-icon" viewBox="0 0 24 24" fill="none">
                      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      <line x1="1" y1="1" x2="23" y2="23" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  )}
                </button>
                <div className="input-glow"></div>
              </div>
            </div>
            
            <div className="verification-section">
              <button
                type="button"
                className={`verification-btn ${isVerified ? 'verified' : ''}`}
                onClick={handleVerification}
                disabled={isVerifying}
              >
                {isVerified ? (
                  <>
                    <span className="success-icon">✓</span>
                    验证完成
                  </>
                ) : (
                  '人机验证'
                )}
              </button>
            </div>
            
            {/* 错误信息显示 */}
            {error && (
              <div className="error-message">
                {error}
              </div>
            )}
            
            <button 
              type="submit" 
              className="login-btn"
              disabled={isLoading || !isVerified}
            >
              {isLoading ? '登录中...' : '登录'}
            </button>
          </form>
          
          <div className="divider">
            <span>或</span>
          </div>
          
          <div className="third-party-login">
            <button
              className="third-party-btn wechat"
              onClick={() => handleThirdPartyLogin('微信')}
            >
              <svg className="icon" viewBox="0 0 24 24">
                <path d="M8.5 12.5c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm7 0c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2z"/>
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
              </svg>
              微信登录
            </button>
            
            <button
              className="third-party-btn qq"
              onClick={() => handleThirdPartyLogin('QQ')}
            >
              <svg className="icon" viewBox="0 0 24 24">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
              </svg>
              QQ登录
            </button>
          </div>
          
          <div className="login-footer">
            <a href="#" className="forgot-password">忘记密码？</a>
            <a href="#" className="register-link">立即注册</a>
          </div>
        </div>
      </div>
      
      <VerifyModal
        isOpen={showVerifyModal}
        onClose={handleVerifyClose}
        onSuccess={handleVerifySuccess}
      />
    </div>
  )
}

export default Index
